<!DOCTYPE html>
<html>
<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>黑马面面</title>
    <meta name="description" content="黑马面面">
    <meta name="keywords" content="黑马面面">
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../css/element-ui.css">
    <link rel="stylesheet" href="../css/quill.core.css"/>
    <link rel="stylesheet" href="../css/quill.snow.css"/>
    <link rel="stylesheet" href="../css/quill.bubble.css"/>
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <!-- 引入组件库 -->
    <script src="../js/vue.js"></script>
    <script src="../js/element-ui.js"></script>
    <script src="../js/vue-quill-editor.js"></script>
    <script src="../js/base.js"></script>
    <script src="../js/axios-0.18.0.js"></script>
</head>
<!--增：添加题目和修改的一起
​    删：删除按钮
​    查：初始化数据：initFormData   -->
<body class="hold-transition">
<div id="app">
    <!--{{formData}}-->
    <div class="app-container">
        <div class="box common-table-border" style="margin-top: 15px;min-height: calc(100vh - 55px);">
            <h2 class="titleInfo"><span>{{this.coursename}}</span></h2>
            <!--题目列表-->
            <el-button class="el-icon-circle-plus-outline" @click="add">添加一条</el-button>
            <el-button @click="getList()">刷新页面（未保存会取消）</el-button>
            <template>
                <div>
                    <el-table :data="tableData" style="width: 100%">
                        </el-table-column>
                        <el-table-column label="序号" align="center" width="50px">
                            <template slot-scope="scope">
                                <span>{{ scope.$index + 1 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="题干" align="center" width="500px">
                            <template slot-scope="scope">
                                <el-input v-if="scope.row.flag" v-model="scope.row.subject"
                                          placeholder="不填默认为空"></el-input>
                                <span v-else>{{scope.row.subject}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="time" label="录入时间" align="center">
                            <template slot-scope="scope">
                                {{ scope.row.createDate | dateTransform }}
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" align="center">
                            <template slot-scope="scope">
                                {{ scope.row.status == 0 ? '禁用' : '已启用'}}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width"
                                         width="450px">
                            <template slot-scope="scope">
                                <div class="operation">
                                    <!--修改 完成按钮-->
                                    <el-button-group>
                                        <!--!scope.row.flag就是非1-->
                                        <el-button size="mini" type="danger"
                                                   @click="cancelCommit(scope.$index,scope.row.flag)"
                                                   v-if="scope.row.flag">
                                            <i class="el-icon-remove-outline" aria-hidden="true"></i> 取消
                                        </el-button>
                                        <el-button type="primary" size="mini"
                                                   @click="handlechange(scope.$index, scope.row)"
                                                   v-else><i
                                                class="fa fa-pencil-square-o"
                                                aria-hidden="true"></i> 修改
                                        </el-button>
                                    </el-button-group>

                                    <!--下架 启用按钮-->
                                    <el-button-group>
                                        <el-button type="danger" size="mini" @click="handleClose(scope.row)"
                                                   v-if="scope.row.status"><i
                                                class="el-icon-switch-button"
                                                aria-hidden="true"></i> 下架
                                        </el-button>
                                        <el-button size="mini" type="primary" @click="handleOpen(scope.row)" v-else>
                                            <i class="fa fa-pencil-square-o" aria-hidden="true"></i>启用
                                        </el-button>
                                    </el-button-group>

                                    <!--删除 取消按钮-->
                                    <el-button-group>
                                        <el-button size="mini" type="danger"
                                                   @click="handleDeleted(scope.$index,scope.row)"
                                                   v-if="!scope.row.flag">
                                            <i class="fa fa-trash-o" aria-hidden="true"></i>
                                            删除
                                        </el-button>
                                        <el-button type="primary" size="mini" @click="handleCommit(scope.$index)"
                                                   v-else><i
                                                class="fa fa-pencil-square-o"
                                                aria-hidden="true"></i> 完成
                                        </el-button>
                                    </el-button-group>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </template>


        </div>
        <!--分页-->
        <div class="pagination-container">
            <el-pagination
                    class="pagiantion"
                    v-show="pagination.total>0"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pagination.currentPage"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pagination.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total">
            </el-pagination>
        </div>
    </div>
</div>
</body>

<script>
    Vue.use(VueQuillEditor);
    new Vue({
        el: '#app',
        data() {

            return {
                coursename: '',
                tableData: [
                    {
                        flag: 1,
                        name: '',
                    }
                ],
                /* tableData: [{
                     date: '2021-03-02',
                     name: '头痛',
                 }],*/
                pagination: {
                    total: 0,
                    currentPage: 1,
                    pageSize: 10
                },
                // items: [],
                /*appPath: app_path,
                baseData: base,
                questionId: 0,*/
                /*// 学科下拉列表
                courses: [],
                // 目录下拉列表
                catalogs: [],
                // 企业下拉列表
                companys: [],
                // 地区级联选择器
                dicts: [],
                cascaderProps: {
                    label: 'dataValue',
                    value: 'id',
                    children: 'subList'
                },
                // 方向下拉列表
                industrys: [],
                // 标签下拉列表
                tags: [],
                // 单选题型：选中的索引
                radioIndex: '',
                formData: {
                    // 试题id
                    id: 0,
                    // 是否精选题目
                    is_classic: 0,
                    // 学科id
                    courseId: '',
                    // 目录id
                    catalogId: '',
                    // 企业id
                    companyId: '',
                    // 区域ids
                    cityIds: [],
                    // 方向ids
                    industryIds: [],
                    // 题型
                    type: 1,
                    // 难度
                    difficulty: 1,
                    // 题干
                    subject: '',
                    // 选项
                    questionItemList: [{
                        id: 0,
                        content: '',
                        isRight: false,
                        imgUrl: ""
                    }, {
                        id: 0,
                        content: '',
                        isRight: false,
                        imgUrl: ""
                    }, {
                        id: 0,
                        content: '',
                        isRight: false,
                        imgUrl: ""
                    }, {
                        id: 0,
                        content: '',
                        isRight: false,
                        imgUrl: ""
                    }, {
                        id: 0,
                        content: '',
                        isRight: false,
                        imgUrl: ""
                    }, {
                        id: 0,
                        content: '',
                        isRight: false,
                        imgUrl: ""
                    }],
                    // 答案解析
                    analysis: '',
                    // 视频解析
                    analysisVideo: '',
                    // 题目备注
                    remark: '',
                    // 试题标签
                    tagIds: ''
                },
                editorOption: {
                    placeholder: "输入任何内容，支持html"
                },*/
                /*rules: {
                    courseId: [{
                        required: true,
                        message: '请选择',
                        trigger: 'change'
                    }],
                    catalogId: [{
                        required: true,
                        message: '请选择',
                        trigger: 'change'
                    }],
                    companyId: [{
                        required: true,
                        message: '请选择',
                        trigger: 'change'
                    }],
                    industryIds: [{
                        required: true,
                        message: '请选择',
                        trigger: 'change'
                    }],
                    type: [{
                        required: true,
                        message: '请至少选择一个',
                        trigger: 'change'
                    }],
                    difficulty: [{
                        required: true,
                        message: '请至少选择一个',
                        trigger: 'change'
                    }],
                    subject: [{
                        required: true,
                        message: '请填写',
                        trigger: 'change'
                    }],
                    analysis: [{
                        required: true,
                        message: '请填写',
                        trigger: 'change'
                    }]
                }*/
            }
        },
        components: {
            VueQuillEditor
        },
        created() {
            // 试题分页列表
            this.getList();
            // 获取试题名字
            this.getName();
            /*
            // 学科下拉列表
            this.initCourses();
            // 企业下拉列表
            this.initCompanys();
            // 地区级联选择器
            this.intDicts();
            // 方向下拉列表
            this.initIndustrys();
            //初始化数据
            this.initFormData();*/
        },
        filters: {
            dateTransform: (value) => {
                if (value != null) {
                    let index1 = value.lastIndexOf('.');
                    return value.substr(0, index1);
                }

            },
        },
        methods: {
            // 获取题库名字
            getName() {
                // 获取id
                let id = this.getUrlParam("id");
                axios.post('/course/findName.do?id=' + id).then(res => {
                    // 导入试题名字
                    this.coursename = res.data.result.name;
                })
            },
            // 设置题目为启用（完成）
            handleOpen(row) {
                axios.post('/subject/EnableStatus.do?id=' + row.id).then(res => {
                    //返回信息
                    this.$message({
                        message: res.data.message,
                        type: res.data.flag ? "success" : "error"
                    });
                    //刷新列表
                    this.getList();
                })
            },
            // 设置题目为禁用（完成）
            handleClose(row) {
                axios.post('/subject/DisableStatus.do?id=' + row.id).then(res => {
                    //返回信息
                    this.$message({
                        message: res.data.message,
                        type: res.data.flag ? "success" : "error"
                    });
                    //刷新列表
                    this.getList();
                })
            },
            // 返回获取url的参数（完成）
            getUrlParam(name) {
                let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
                let r = window.location.search.substr(1).match(reg);
                if (r != null) return unescape(r[2]);
                return null;
            },
            // 分页（完成）
            getList() {
                // 获取id
                let id = this.getUrlParam("id");
                console.log("id=" + id);
                axios.post('/subject/findPage.do?id=' + id, this.pagination).then(res => {
                    if (res.data.flag) {
                        // 绑定数据
                        this.tableData = res.data.result.records;
                        // 总记录数
                        this.pagination.total = res.data.result.total;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
            },
            // 分页用的
            handleSizeChange(val) {
                this.pagination.pageSize = val;

                this.pagination.currentPage = 1;
                this.getList();
            },
            // 分页用的
            handleCurrentChange(val) {
                this.pagination.currentPage = val;
                this.getList();
            },
            // 提交题目（完成）
            handleCommit($index) {
                // 获取id
                let id = this.getUrlParam("id");
                axios.post('/subject/add.do?id=' + id, this.tableData[$index]).then(res => {
                    // 返回信息
                    this.$message({
                        message: res.data.message,
                        type: res.data.flag ? "success" : "error"
                    });
                    if (res.data.flag) {
                        // 把数据固定到页面上
                        this.$set(this.tableData[$index], 'flag', 0)
                        // 刷新列表
                        this.getList();
                    }
                })

                /*刷新列表*/
                // this.getList();
                /*                this.tableData.map(item => {
                                    if (item.status) {
                                        item.status = 0;
                                    }
                                    return item;
                                })*/
            },
            //取消提交题目（完成）
            cancelCommit($index, flag) {
                // 转换状态
                this.$set(this.tableData[$index], 'flag', 0)
                // 如果是新增就把这一行删了
                if (flag === 2) {
                    //删除
                    this.tableData.splice($index, 1);
                }
            },
            //删除题目(完成)
            handleDeleted($index, row) {
                console.log(this.tableData);
                this.$confirm('此操作将永久删除该条模板, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/subject/delete.do?id=' + row.id).then(res => {
                        //返回信息
                        this.$message({
                            message: res.data.message,
                            type: res.data.flag ? "success" : "error"
                        });
                        //成功就刷新
                        if (res.data.flag) {
                            // 刷新列表
                            this.getList();
                            this.tableData.splice($index, 1);
                        }
                    })
                })
            },
            //点击修改
            handlechange($index, row) {
                this.$set(this.tableData[$index], 'flag', 1)
            },
            //添加题目
            add() {
                /*添加试题*/
                this.tableData.push({
                    flag: 2
                });
                console.log("---------");
            },
            /*原*/
            /*            filterTag(value, row) {
                            return row.tag === value;
                        },
                        formatter(row, column) {
                            return row.address;
                        },*/
            //重置文本框
            /*resetForm(formName) {
                this.$refs[formName].resetFields();
            },*/
            //获取url参数
            /*getUrlParam(name) {
                let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
                let r = window.location.search.substr(1).match(reg);
                if (r != null) return unescape(r[2]);
                return null;
            },*/
            /*initQuestionById() {
                let questionId = parseInt(this.getUrlParam("questionId"), 10);
                if (questionId) {
                    // 初始化试题
                    this.questionId = questionId;
                    this.initFormData();
                }
            },*/
            // 初始化试题
            /*initFormData() {
                console.log("初始化试题返回结果：");

                let response = {
                    data: {
                        "rows": [
                            {
                                "answerIsRight": false,
                                "courseName": "java",
                                "createDate": "2019-08-08 00:00:00.0",
                                "creator": "admin",
                                "difficulty": 1,
                                "id": 1,
                                "isFamous": false,
                                "isFavorite": false,
                                "isFinished": false,
                                "number": "",
                                "reviewLog": {
                                    "comments": "通过",
                                    "createDate": "2019-08-14 10:35:24.0",
                                    "id": 4,
                                    "reviewer": "admin",
                                    "status": 1
                                },
                                "status": 0,
                                "subject": "<p>springmvc，mybatis的执行流程，spring中事物的管理</p>\r\n",
                                "type": 5,
                                "usedQty": "0"
                            }, {
                                "answerIsRight": false,
                                "courseName": "学科----",
                                "createDate": "2019-08-08 00:00:00.0",
                                "creator": "admin",
                                "difficulty": 1,
                                "id": 1,
                                "isFamous": false,
                                "isFavorite": false,
                                "isFinished": false,
                                "number": "",
                                "reviewLog": {
                                    "comments": "通过",
                                    "createDate": "2020-08-14 10:35:24.0",
                                    "id": 4,
                                    "reviewer": "admin",
                                    "status": 1
                                },
                                "status": 0,
                                "subject": "<p>题干*--------------------------</p>\r\n",
                                "type": 5,
                                "usedQty": "0"
                            }],
                        "dynamicValidateForm": {
                            "domains": [{
                                "value": '123'
                            }],
                        },
                        "flag": true,
                        "message": "获取成功",
                        "result": {
                            "analysis": "<p>图片选择</p>",
                            "analysisVideo": "",
                            "answerIsRight": false,
                            "catalog": {
                                "courseId": 1,
                                "courseName": "Java",
                                "createDate": "2019-08-08 00:00:00.0",
                                "id": 1,
                                "name": "Java基础",
                                "status": 0,
                                "userId": 1
                            },
                            "catalogId": 1,
                            "company": {
                                "city": "北京",
                                "id": 1,
                                "industryList": [
                                    {
                                        "id": 1,
                                        "name": "电商平台"
                                    },
                                    {
                                        "id": 2,
                                        "name": "金融服务"
                                    }
                                ],
                                "industryNameList": [
                                    "电商平台",
                                    "金融服务"
                                ],
                                "shortName": "北京淘宝网"
                            },
                            "companyId": 1,
                            "createDate": "2019-08-22 10:52:49.0",
                            "difficulty": 1,
                            "id": 654,
                            "isFamous": false,
                            "isFavorite": false,
                            "isFinished": false,
                            "number": "",
                            "questionItemList": [
                                {
                                    "content": "aaa",
                                    "id": 72,
                                    "imgUrl": "",
                                    "isRight": true
                                },
                                {
                                    "content": "bbb",
                                    "id": 73,
                                    "imgUrl": "",
                                    "isRight": false
                                },
                                {
                                    "content": "cccc",
                                    "id": 74,
                                    "imgUrl": "",
                                    "isRight": false
                                },
                                {
                                    "content": "ddd",
                                    "id": 75,
                                    "imgUrl": "",
                                    "isRight": false
                                }
                            ],
                            "remark": "图片选择",
                            "reviewStatus": 0,
                            "status": 0,
                            "subject": "<p>图片选择</p>",
                            "tagList": [
                                {
                                    "id": 1,
                                    "name": "String字符串"
                                },
                                {
                                    "id": 2,
                                    "name": "Java类与对象"
                                }
                            ],
                            "tagNameList": [
                                "String字符串",
                                "Java类与对象"
                            ],
                            "type": 1,
                            "userId": 1
                        }
                    }

                }
                this.items = response.data.rows;
                console.log(this.items);
                this.transformFormData(response.data.result);
            },*/
            // 转换后端返回的数据
            /*transformFormData(result) {
                let t = this;

                let companyId = result.companyId;
                let cityIds = this.transformCityIds(companyId);
                let industryIds = [];
                result.company.industryList.forEach(val => {
                    industryIds.push(val.id);
                });
                let type = result.type;
                let questionItemList = result.questionItemList;
                let tagIds = [];
                result.tagList.forEach(val => {
                    tagIds.push(val.id);
                });
                // 试题id
                t.formData.id = result.id;
                // 学科id
                t.formData.courseId = result.catalog.courseId;
                // 目录id
                t.formData.catalogId = result.catalogId;
                // 企业id
                t.formData.companyId = companyId;
                // 区域ids
                t.formData.cityIds = cityIds;
                // 方向ids
                t.formData.industryIds = industryIds;
                // 题型
                t.formData.type = type;
                // 难度
                t.formData.difficulty = result.difficulty;
                // 题干
                t.formData.subject = result.subject;
                // 选项
                t.formData.questionItemList = result.questionItemList;
                // 答案解析
                t.formData.analysis = result.analysis;
                // 视频解析
                t.formData.analysisVideo = result.analysisVideo;
                // 题目备注
                t.formData.remark = result.remark;
                // 视频解析
                t.formData.tagIds = tagIds;

                // 单选题型时，回显radio选中
                if (type === 1) {
                    let radioIndex = questionItemList.findIndex(val => {
                        return val.isRight === true;
                    });
                    if (radioIndex !== -1) {
                        this.radioIndex = radioIndex;
                    }
                }

                let courseId = this.formData.courseId;
                let course = this.courses.find((val) => {
                    return val.id === courseId;
                });
                this.catalogs = course.catalogList;
                this.tags = course.tagList;
            },*/
            // 学科下拉列表
            // initCourses() {
            //     let t = this;
            //     axios.get('/course/findListAll.do').then(response => {
            //         if (response.data.flag) {
            //             t.courses = response.data.result;
            //         }
            //     });
            //
            // },
            /*changeCourse() {
                let courseId = this.formData.courseId;
                let course = this.courses.find((val) => {
                    return val.id === courseId;
                });
                this.catalogs = course.catalogList;
                this.formData.catalogId = '';
                this.formData.tagIds = [];

                //this.initTags(tagList);
                this.tags = course.tagList;
            },*/
            // 企业下拉列表
            /*            initCompanys() {
                            let t = this;
                            /!*axios.get('/company/findListAll.do').then(response => {
                            if (response.data.flag) {
                                t.companys = response.data.result;
                                // 初始化试题(初始化公司时，需要在初始化公司之后再初始化)
                                this.initQuestionById()
                            }
                        });*!/

                            // 初始化试题(初始化公司时，需要在初始化公司之后再初始化)
                            this.initQuestionById()
                        },*/
            /*changeCompany(val) {
                let companyId = this.formData.companyId;

                this.formData.cityIds = this.transformCityIds(companyId);

                let company = this.companys.find((item) => {
                    return item.id === companyId;
                });
                let industryIds = [];
                company.industryList.forEach(val => {
                    industryIds.push(val.id);
                });
                this.formData.industryIds = industryIds;
            },*/
            // 地区级联选择器
            /*intDicts() {
                let t = this;
                // 获取省市数据
                axios.get('/dict/findListByType.do').then(response => {
                    if (response.data.flag) {
                        t.dicts = response.data.result;
                    }
                });


            },*/
            // 方向下拉列表
            /*initIndustrys() {
                let t = this;
                axios.get('/industry/findAll.do').then(response => {
                    if (response.data.flag) {
                        t.industrys = response.data.result;
                    }
                })
            }
            t.industrys = response.data.result;*!/
            },*/
            // 切换题型，重置选项选中状态
            /*            changeType(val) {
                            this.formData.questionItemList.forEach(val => {
                                val.isRight = false;
                            });
                            this.radioIndex = '';
                        },*/
            // 切换单选按钮，改变选中状态
            /*            changeRadio(index) {
                            let questionItemList = this.formData.questionItemList;
                            questionItemList.forEach(val => {
                                val.isRight = false;
                            });
                            questionItemList[index].isRight = true;
                        },*/
            // 转换选中省市数据
            /*transformCityIds(companyId) {
                let cityIds = [];

                // 由于后端只返回了cityId,所以需要前端遍历所有省市,找到provinceId
                let company = this.companys.find((item) => {
                    return item.id === companyId;
                });
                let provinceId = 0;

                let cityId = company.cityId;
                for (let i = 0; i < this.dicts.length; i++) {
                    let dict = this.dicts[i];
                    let index = dict.subList.findIndex(subDict => {
                        return subDict.id === cityId;
                    });
                    if (index !== -1) {
                        provinceId = dict.id;
                        break;
                    }
                }
                if (!provinceId) {
                    cityIds = [];
                } else {
                    cityIds = [provinceId, cityId];
                }
                return cityIds;
            },*/
            // 自定义上传的实现
            /*handleHttpRequest(params, index) {
                let file = params.file;

                let formData = new FormData();
                formData.append(file.name, file);
                let response = {};
            },*/
            // 提交表单
            /*createItem() {
                // 表单校验
                let isValid = false;
                this.$refs['formData'].validate((valid) => {
                    isValid = valid;
                });
                if (!isValid) {
                    return;
                }
                let formData = this.formData;

                // 包装企业相关数据
                let industrys = this.industrys;
                let industryList = [];
                formData.industryIds.forEach(industryId => {
                    let industry = industrys.find(industry => {
                        return industry.id === industryId;
                    });
                    // TODO 会有新增的方向
                    //industryList.push(industry);
                    if (industry) {
                        industryList.push(industry);
                    } else {
                        industryList.push({
                            id: 0,
                            name: industryId
                        });
                    }

                });
                let company = {
                    id: formData.companyId,
                    cityId: formData.cityIds[1],
                    industryList: industryList
                };
                formData.company = company;
                // 包装选项相关数据
                let questionItemList = this.formData.questionItemList;
                questionItemList.forEach(val => {
                    val.isRight = val.isRight ? 1 : 0;
                });
                // 包装标签相关数据
                let tags = this.tags;
                let tagList = [];
                formData.tagIds.forEach(tagId => {
                    let tag = tags.find(tag => {
                        return tag.id === tagId;
                    });
                    // TODO 会有新增的标签
                    //tagList.push(tag);
                    if (tag) {
                        tagList.push(tag);
                    } else {
                        tagList.push({
                            id: 0,
                            name: tagId
                        });
                    }
                });
                formData.tagList = tagList;
                console.log("新增更新题库请求参数：" + JSON.stringify(this.formData));

                axios.post('/question/addOrUpdate.do', this.formData).then(response => {
                    if (response.data.flag) {
                        // 返回到上一级
                        if (!this.formData.is_classic) {
                            setTimeout(function () {
                                    window.location.href = "questionBasicList.html";
                                }
                                , 1000);
                        } else {
                            setTimeout(function () {
                                window.location.href = "questionClassicList.html";
                            }, 1000);
                        }
                    } else {
                        this.$message.error(response.data.message);
                    }
                });


            },*/
            // 取消提交
            /*cancelItem() {
                if (!this.formData.is_classic) {
                    window.location.href = "questionBasicList.html";
                } else {
                    window.location.href = "questionClassicList.html";
                }
            }*/
        }

    })
</script>
</html>
